import VueRouter from 'vue-router';
import Vue from 'vue';
Vue.use(VueRouter)

// 导入对应的页面组件
// import Home from '@/views/Home.vue'
// import Topic from '@/views/Topic.vue'
// import Category from '@/views/Category.vue'
// import Cart from '@/views/Cart.vue'
// import User from '@/views/User.vue'
// import searchPop from '@/views/searchPop.vue'
// import Detail from '@/views/Productdetail.vue'  //详情页

const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch((err) => err);
};

// 第一步：创建路由配置
const routes = [
    { path: '', redirect: '/home' }, // 路由重定向
    {
        path: '/home',
        component: () => import('@/views/Home.vue'), // 路由懒加载
        name: 'home',
        children: [
            {
                path: 'searchpop',
                component: () => import('@/views/searchPop.vue'),
                name: 'searchpop',
                meta: {
                    showtarbar: false
                }
            }
        ],
        meta: {
            showtarbar: true
        }
    },
    {
        path: '/topic',
        component: () => import('@/views/Topic.vue'),
        name: 'topic',
        meta: {
            showtarbar: true
        }
    },
    {
        path: '/category',
        component: () => import('@/views/Category.vue'),
        name: 'category',
        meta: {
            showtarbar: true
        }
    },
    {
        path: '/cart',
        component: () => import('@/views/Cart.vue'),
        name: 'cart',
        meta: {
            showtarbar: true
        }
    },
    {
        path: '/user',
        component: () => import('@/views/User.vue'),
        name: 'user',
        meta: {
            showtarbar: true
        }
    },
    {
        path: '/detail',
        component: () => import('@/views/Productdetail.vue'),
        name: 'detail',
        meta: {
            showtarbar: false
        }
    },
]

// 第二步：创建路由实例对象
const router = new VueRouter({
    mode: 'history',
    routes
})

// 添加路由守卫 (注意：这是全局路由守卫，该整个项目的所有路由跳转都要经过该守卫)
router.beforeEach((to, from, next) => {
    // 当跳转到购物车页 做一个登录守卫判断

    if (to.path == '/cart') {
        //当是购物车页的时候，判断是否登陆过
        let user = localStorage.getItem('user')  // string 或 null
        if (user) {
            // 已登录,正常放行
            next()
        } else {
            //  提示请先登录
            Vue.prototype.$toast.fail('请先登录')
            setTimeout(() => {
                next('/user')
            }, 1000)
        }
    } else {
        // 非购物车页正常放行
        next()
    }

})



export default router

